<template>
  <div class="job-applications">
    <div class="page-header">
      <h2>我的申请记录</h2>
      <div class="application-stats">
        <div class="stat-item">
          <div class="stat-title">申请总数</div>
          <div class="stat-value">{{ Array.isArray(applications) ? applications.length : 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">面试邀请</div>
          <div class="stat-value">{{ Array.isArray(applications) ? applications.filter(app => app.status === 'interview' || app.status === 'interviewing' || app.status === 2).length : 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">录用机会</div>
          <div class="stat-value">{{ Array.isArray(applications) ? applications.filter(app => app.status === 'offer').length : 0 }}</div>
        </div>
      </div>
    </div>
    
    <div class="filter-section">
      <div class="filter-item">
        <el-select v-model="filters.status" placeholder="申请状态" clearable>
          <el-option
            v-for="status in statusOptions"
            :key="status.value"
            :label="status.label"
            :value="status.value"
          />
        </el-select>
      </div>
      
      <div class="filter-item">
        <el-select v-model="filters.timeRange" placeholder="申请时间" clearable>
          <el-option
            v-for="timeRange in timeRangeOptions"
            :key="timeRange.value"
            :label="timeRange.label"
            :value="timeRange.value"
          />
        </el-select>
      </div>
      
      <div class="filter-item search-input">
        <el-input
          v-model="filters.keyword"
          placeholder="搜索职位或公司名称"
          clearable
          :prefix-icon="Search"
        />
      </div>
    </div>

    <div class="applications-table-wrapper">
      <el-table
        v-loading="loading"
        :data="filteredApplications"
        style="width: 100%"
        border
        stripe
        row-key="id"
      >
        <el-table-column prop="jobTitle" label="职位名称" min-width="180">
          <template #default="{ row }">
            <div class="job-title">{{ row.jobTitle }}</div>
            <div class="company-name">{{ row.companyName }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="applyTime" label="申请时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.applyTime || row.applicationDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="申请状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
              effect="light"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
            <div v-if="row.status === 'interview' || row.status === 'interviewing' || row.status === 2" class="status-detail">
              <el-tag type="success" size="small" effect="plain" class="interview-tag">
                <el-icon><Calendar /></el-icon>
                面试邀请
              </el-tag>
            </div>
            <div v-if="row.status === 'rejected' || row.status === 3" class="status-detail">
              <el-tag type="danger" size="small" effect="plain">
                不合适
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="feedback" label="反馈" min-width="200">
          <template #default="{ row }">
            <div v-if="row.feedback" class="feedback-content">
              {{ row.feedback }}
            </div>
            <div v-else-if="row.status === 'interview' || row.status === 'interviewing' || row.status === 2" class="feedback-content">
              <span class="highlight-text">您已收到面试邀请！</span> 请查看详情安排面试时间。
            </div>
            <div v-else-if="row.status === 'rejected' || row.status === 3" class="feedback-content muted-text">
              很遗憾，该职位与您当前不匹配
            </div>
            <div v-else-if="row.status === 'offer'" class="feedback-content">
              <span class="highlight-text">恭喜！您已获得录用机会</span>
            </div>
            <div v-else class="feedback-content muted-text">
              暂无反馈信息
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              
              
              <el-button 
                v-if="row.status === 'interview' || row.status === 'interviewing' || row.status === 2"
                type="success" 
                circle
                @click="viewInterviewDetails(row.id)"
                title="查看面试安排"
              >
                <el-icon><Calendar /></el-icon>
              </el-button>
              
              
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="Array.isArray(filteredApplications) ? filteredApplications.length : 0"
        />
      </div>
    </div>
    
    <!-- 面试详情弹窗 -->
    <el-dialog
      v-model="interviewDialogVisible"
      title="面试详情"
      width="500px"
      :close-on-click-modal="false"
      class="interview-dialog"
    >
      <div class="interview-detail">
        <div class="interview-header">
          <h3 class="interview-job-title">{{ currentInterview.jobTitle }}</h3>
          <div class="interview-company">{{ currentInterview.companyName }}</div>
          
          <div class="interview-status">
            <el-tag 
              :type="currentInterview.status === 'confirmed' ? 'success' : 'warning'"
              effect="light"
            >
              {{ interviewStatusMap[currentInterview.status] || '待确认' }}
            </el-tag>
          </div>
        </div>
        
        <div class="interview-info-section">
          <div class="info-item">
            <div class="info-label">
              <el-icon><Calendar /></el-icon>面试时间
            </div>
            <div class="info-value">{{ formatDateTime(currentInterview.interviewTime) }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">
              <el-icon><Location /></el-icon>面试地点
            </div>
            <div class="info-value">{{ currentInterview.interviewLocation }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">
              <el-icon><VideoCamera /></el-icon>面试形式
            </div>
            <div class="info-value">{{ currentInterview.interviewType }}</div>
          </div>
          
          
        </div>
        
        <div class="interview-instructions">
          <div class="info-label">面试说明</div>
          <div class="instructions-content">{{ currentInterview.instructions }}</div>
        </div>
      </div>
      
     
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  View,
  More,
  Search,
  Document,
  ChatDotRound,
  CircleClose,
  Calendar,
  Timer,
  OfficeBuilding,
  Location,
  VideoCamera,
  User
} from '@element-plus/icons-vue'
import { getUserApplications, updateApplicationStatus, getApplicationDetail, updateInterviewStatus } from '@/api/application'
import { useRouter } from 'vue-router'

const router = useRouter()

// 申请列表数据
const applications = ref([])
const upcomingInterviews = ref([])
const loading = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)

// 面试对话框状态
const interviewDialogVisible = ref(false)
const currentInterview = ref({
  id: null,
  jobTitle: '',
  companyName: '',
  interviewTime: '',
  interviewLocation: '',
  interviewType: '', // 线上/线下
  interviewer: '',
  instructions: '',
  status: ''
})

// 表格状态
const loadingInterview = ref(false)

// 面试状态显示
const interviewStatusMap = {
  'pending': '待确认',
  'confirmed': '已确认',
  'rescheduled': '已改期',
  'completed': '已完成',
  'canceled': '已取消'
}

// 筛选条件
const filters = reactive({
  status: '',
  timeRange: '',
  keyword: ''
})

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'reviewing', label: '审核中' },
  { value: 'interview', label: '面试中' },
  { value: 'offer', label: '已录用' },
  { value: 'rejected', label: '已拒绝' },
  { value: 'canceled', label: '已撤销' }
]

// 时间范围选项
const timeRangeOptions = [
  { value: '7days', label: '最近7天' },
  { value: '30days', label: '最近30天' },
  { value: '90days', label: '最近3个月' },
  { value: 'allTime', label: '全部时间' }
]

// 筛选后的职位申请列表
const filteredApplications = computed(() => {
  // 确保返回的始终是数组
  if (!Array.isArray(applications.value)) {
    return []
  }
  
  // 实现筛选逻辑，如果有筛选条件则应用
  let result = applications.value
  
  // 按状态筛选
  if (filters.status) {
    // 处理状态筛选
    if (filters.status === 'interview') {
      // 面试状态需特殊处理，同时匹配字符串'interview'/'interviewing'和数字2
      result = result.filter(app => 
        app.status === 'interview' || 
        app.status === 'interviewing' || 
        app.status === 2
      )
    } else if (filters.status === 'rejected') {
      // 同样处理拒绝状态，匹配字符串'rejected'和数字3
      result = result.filter(app => app.status === 'rejected' || app.status === 3)
    } else {
      // 其他状态正常匹配
      result = result.filter(app => app.status === filters.status)
    }
  }
  
  // 按关键词筛选（职位名称或公司名称）
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(app => 
      (app.jobTitle && app.jobTitle.toLowerCase().includes(keyword)) || 
      (app.companyName && app.companyName.toLowerCase().includes(keyword))
    )
  }
  
  // 按时间范围筛选
  if (filters.timeRange) {
    const now = new Date()
    let startDate
    
    switch(filters.timeRange) {
      case '7days':
        startDate = new Date(now.setDate(now.getDate() - 7))
        break
      case '30days':
        startDate = new Date(now.setDate(now.getDate() - 30))
        break
      case '90days':
        startDate = new Date(now.setDate(now.getDate() - 90))
        break
      default:
        startDate = null
    }
    
    if (startDate) {
      result = result.filter(app => {
        // 兼容两种可能的日期字段名
        const dateField = app.applyTime || app.applicationDate
        const appDate = dateField ? new Date(dateField) : null
        return appDate && appDate >= startDate
      })
    }
  }
  
  return result
})

// 添加对筛选条件的监听，以便在筛选条件变化时刷新列表
watch([filters.status, filters.timeRange, filters.keyword], () => {
  console.log('筛选条件变化：', filters)
})

// 调试函数：在控制台详细打印申请数据
const debugApplications = () => {
  console.log('==== 应用记录调试信息 ====')
  console.log(`总记录数: ${applications.value.length}`)
  
  if (Array.isArray(applications.value) && applications.value.length > 0) {
    console.log('完整数据样本:', applications.value[0])
    
    applications.value.forEach((app, index) => {
      console.log(`申请 #${index+1}:`, {
        id: app.id,
        jobTitle: app.jobTitle,
        companyName: app.companyName,
        status: app.status,
        statusType: typeof app.status,
        statusText: getStatusText(app.status),
        applyTime: app.applyTime || app.applicationDate,
        feedback: app.feedback,
        interviewInfo: app.interviewInfo || app.interview || '无面试信息'
      })
    })
    
    // 统计各状态数量
    const statusCounts = {}
    applications.value.forEach(app => {
      // 转换数字状态为字符串，以便统一展示
      const statusKey = typeof app.status === 'number' ? `数字:${app.status}` : app.status
      statusCounts[statusKey] = (statusCounts[statusKey] || 0) + 1
    })
    console.log('状态统计:', statusCounts)
    
    // 特别检查面试状态的记录
    const interviews = applications.value.filter(app => 
      app.status === 'interview' || app.status === 'interviewing' || app.status === 2
    )
    console.log(`面试邀请数量: ${interviews.length}`)
    if (interviews.length > 0) {
      console.log('面试记录:', interviews)
    } else {
      // 如果没有面试记录，检查数据中可能包含面试信息的其他字段
      const potentialInterviews = applications.value.filter(app => 
        app.interviewInfo || app.interview || app.interviewTime || app.feedback?.includes('面试')
      )
      if (potentialInterviews.length > 0) {
        console.log('可能包含面试信息的记录:', potentialInterviews)
      }
    }
  } else {
    console.log('无申请记录')
  }
  console.log('========================')
}

// 获取申请记录
const fetchApplications = async () => {
  try {
    loading.value = true
    const response = await getUserApplications()
    
    if (response && response.code === 200) {
      // 调试输出，查看实际数据结构
      console.log('申请数据：', response.data)
      
      // 确保applications.value始终是数组
      const data = response.data
      if (Array.isArray(data)) {
        applications.value = data
      } else if (data && Array.isArray(data.records)) {
        // 如果API返回格式是{records: [...], total: x}这种分页格式
        applications.value = data.records
      } else {
        console.warn('API返回的数据不是数组格式:', data)
        applications.value = []
      }
      
      // 调用详细调试函数
      debugApplications()
    } else {
      applications.value = [] // 出错时重置为空数组
      ElMessage.error(response?.message || '获取申请记录失败')
    }
  } catch (error) {
    console.error('获取申请记录失败', error)
    applications.value = [] // 确保出错时也重置为空数组
    ElMessage.error('获取申请记录失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 获取即将到来的面试
const fetchInterviews = async () => {
  try {
    // API调用获取面试信息
    upcomingInterviews.value = [] // 假数据，实际项目中应该从API获取
  } catch (error) {
    console.error('获取面试信息失败', error)
  }
}

// 查看申请详情
const viewApplicationDetail = (id) => {
  router.push(`/my/application/${id}`)
}

// 查看面试详情，打开包含面试时间地点的弹窗
const viewInterviewDetails = async (applicationId) => {
  if (!applicationId) {
    ElMessage.error('申请ID不能为空')
    return
  }

  try {
    loading.value = true
    
    // 尝试先获取专门的面试详情
    let interviewData = null
    
    
    // 如果没有获取到面试详情，则获取申请详情
    if (!interviewData) {
      const applicationRes = await getApplicationDetail(applicationId)
      if (applicationRes && applicationRes.code === 200) {
        // 从申请详情中提取可能的面试信息
        interviewData = applicationRes.data
        console.log('从申请详情中获取到的数据:', interviewData)
      } else {
        throw new Error(applicationRes?.message || '获取详情失败')
      }
    }
    
    // 解析面试时间信息（从processNote中提取）
    let interviewTime = interviewData.interviewTime
    if (!interviewTime && interviewData.processNote) {
      const match = interviewData.processNote.match(/面试时间:\s*([\d-]+\s*[\d:]+)/)
      if (match && match[1]) {
        interviewTime = match[1].trim()
      }
    }
    
    // 构建面试详情对象
    currentInterview.value = {
      id: interviewData.id || applicationId,
      jobTitle: interviewData.jobTitle || '未知职位',
      interviewTime: interviewTime || interviewData.updateTime || new Date().toISOString(),
      interviewLocation: interviewData.interviewLocation || interviewData.city || interviewData.location || '待定',
      interviewType: interviewData.interviewType || interviewData.type || '现场面试',
      instructions: interviewData.instructions || interviewData.note || interviewData.processNote || '暂无面试说明',
      status: interviewData.interviewStatus || interviewData.status === 2 ? 'pending' : 'confirmed'
    }
    
    console.log('处理后的面试详情:', currentInterview.value)
    interviewDialogVisible.value = true
  } catch (error) {
    console.error('获取面试详情失败', error)
    ElMessage.error('获取面试详情失败，请稍后再试')
  } finally {
    loading.value = false
  }
}




// 根据状态获取标签类型
const getStatusType = (status) => {
  // 处理数字状态码
  if (typeof status === 'number') {
    const numStatusMap = {
      0: 'info',    // 待处理
      1: 'warning', // 已查看
      2: 'success', // 已邀面试
      3: 'danger'   // 不合适
    }
    return numStatusMap[status] || 'info'
  }
  
  const statusMap = {
    'pending': 'info',
    'reviewing': 'warning',
    'interview': 'success',
    'interviewing': 'success',
    'offer': 'success',
    'rejected': 'danger',
    'canceled': 'info'
  }
  return statusMap[status] || 'info'
}

// 根据状态获取文本
const getStatusText = (status) => {
  // 处理数字状态码
  if (typeof status === 'number') {
    const numStatusMap = {
      0: '待处理',
      1: '已查看',
      2: '面试中',  // 统一将数字2映射为"面试中"
      3: '已拒绝'
    }
    return numStatusMap[status] || `状态${status}`
  }
  
  const statusMap = {
    'pending': '待处理',
    'reviewing': '审核中',
    'interview': '面试中',
    'interviewing': '面试中',
    'offer': '已录用',
    'rejected': '已拒绝',
    'canceled': '已撤销'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return '-'
  
  // 显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '待定'
  
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}年${month}月${day}日 ${hours}:${minutes}`
}

// 初始化
onMounted(() => {
  fetchApplications()
  fetchInterviews()
})
</script>

<style lang="scss" scoped>
.job-applications {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin-bottom: 16px;
      font-weight: 600;
    }
  }
  
  .application-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    
    .stat-item {
      background-color: #f5f7fa;
      border-radius: 8px;
      padding: 16px;
      flex: 1;
      
      .stat-title {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
  
  .filter-section {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    flex-wrap: wrap;
    
    .filter-item {
      width: 200px;
      
      &.search-input {
        flex-grow: 1;
        max-width: 400px;
      }
    }
  }
  
  .applications-table-wrapper {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .job-title {
      font-weight: 500;
      margin-bottom: 4px;
    }
    
    .company-name {
      font-size: 13px;
      color: #606266;
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 状态样式
  .status-detail {
    margin-top: 4px;
  }

  .interview-tag {
    display: flex;
    align-items: center;
    .el-icon {
      margin-right: 4px;
    }
  }

  // 反馈样式
  .feedback-content {
    line-height: 1.5;
    font-size: 13px;
    
    .highlight-text {
      color: #409EFF;
      font-weight: 500;
    }
    
    &.muted-text {
      color: #909399;
    }
  }

  // 面试详情弹窗样式
  .interview-dialog {
    .interview-detail {
      padding: 0 20px;
    }
    
    .interview-header {
      margin-bottom: 24px;
      padding-bottom: 12px;
      border-bottom: 1px solid #EBEEF5;
      position: relative;
      
      .interview-job-title {
        margin: 0 0 8px 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
      
      .interview-company {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
      
      .interview-status {
        position: absolute;
        top: 0;
        right: 0;
      }
    }
    
    .interview-info-section {
      margin-bottom: 20px;
      
      .info-item {
        display: flex;
        margin-bottom: 16px;
        align-items: flex-start;
        
        .info-label {
          min-width: 100px;
          color: #606266;
          font-size: 14px;
          padding-right: 10px;
          display: flex;
          align-items: center;
          
          .el-icon {
            margin-right: 6px;
            font-size: 16px;
            color: #409EFF;
          }
        }
        
        .info-value {
          color: #303133;
          flex: 1;
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
    
    .interview-instructions {
      background: #F8F9FA;
      padding: 12px;
      border-radius: 4px;
      margin-bottom: 20px;
      
      .info-label {
        color: #606266;
        font-size: 14px;
        margin-bottom: 8px;
        font-weight: 500;
      }
      
      .instructions-content {
        color: #303133;
        font-size: 14px;
        line-height: 1.6;
        white-space: pre-line;
      }
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
    }
  }
}
</style> 